class_name ConfigManager
extends Node

# 配置文件的默认路径
static var config_file_path = OS.get_user_data_dir() + "/config.cfg"#"user://config.cfg"

static var instance: ConfigManager

# 默认配置
static var default_ip = "127.0.0.1"
static var default_port = 8080
static var ip: String
static var port: int

# 初始化配置
func _ready():
	instance = self
	print_config_file_path()

static func read_configs() -> void:
	# 检查配置文件是否存在，如果不存在则创建
	if !FileAccess.file_exists(config_file_path):
		create_default_config()
	# 读取配置
	ip = load_config("network", "server_ip", default_ip)
	port = load_config("network", "server_port", default_port)
	# 输出读取到的配置
	#LogLabel.print_log(["IP: ", ip])
	#LogLabel.print_log(["Port: ", port])

# 保存配置
static func save_config(group: String, key: String, value: Variant) -> ConfigFile:
	var config = ConfigFile.new()
	# 加载现有配置文件
	var err = config.load(config_file_path)
	if err != OK:
		LogLabel.print_log(["加载配置失败，正在创建新的配置文件..."])
	# 设置新的值
	config.set_value(group, key, value)
	# 保存配置
	var save_err = config.save(config_file_path)
	if save_err == OK:
		LogLabel.print_log([group, " -> ", key, " = ", value])
		pass
	else:
		LogLabel.print_log(["保存配置失败: ", key])
	return config

# 加载配置，返回指定值或默认值
static func load_config(group: String, key: String, default_value: Variant) -> Variant:
	var config = ConfigFile.new()
	# 尝试加载配置文件
	var err = config.load(config_file_path)
	if err != OK:
		LogLabel.print_log(["加载配置失败，返回默认值"])
		return default_value
	# 获取配置项的值
	return config.get_value(group, key, default_value)

# 创建默认配置文件
static func create_default_config() -> void:
	LogLabel.print_log(["配置文件不存在，创建默认配置..."])
	var group := "network"
	save_config(group, "server_ip", default_ip)
	save_config(group, "server_port", default_port)
	#LogLabel.print_log(["配置文件已保存到：", config_file_path])

# 获取实际存储路径，便于调试
static func print_config_file_path() -> void:
	LogLabel.print_log(["配置文件路径: ", config_file_path])

# 打印指定组的所有数据
static func print_group_data(config: ConfigFile, group_name: String) -> void:
	# 获取指定组的所有键
	var keys = config.get_section_keys(group_name)
	if keys.size() == 0:
		print("该组没有任何数据: " + group_name)
		return
	# 打印组中的键值对
	print("组: " + group_name)
	for key in keys:
		var value = config.get(key)
		print(key + " = " + str(value))
